package com.bodacn.storagescan;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.InputType;
import android.util.Log;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

public class TransActivity extends AppCompatActivity  implements View.OnClickListener {
    private String TAG = this.getClass().getName();
    private final static int MSG_AllowScan=9000;
    private final static int MSG_ScanBarcodeOver=9001;
    private final static int MSG_Detail =9002;
    private final static int MSG_SpinnerOver=9003;
    TextView txt_titleInv, tv_barcodeCaption,tv_ResultInfo;
    FrameLayout liner_title;
    Button btn_Query;
    ImageButton btn_return;
    EditText edit_Barcode,edt_BoxNo,edt_OrderNo,edt_Item;
    Spinner spinnerTrans;
    String serviceUrl="http://192.168.10.12/tvservice";
    String serviceUrlExt  = "/BDService.asmx?wsdl";
    String curLoginUserNo,curLoginUser,curLoginTime;//操作员所属部门等信息;
    String FormType="",Caption="",PrBarcode="",selReason="";
    JSONArray itemJson, resultJSON,detailJSON;
    boolean ScanSign=false;
    Button btn_refreshDetail;
    ListView list_Order;
    private ArrayAdapter<String> adapter;
    String[] spinnerItem={"颜色/尺码错","箱规用错","国家/港口错","合约错","胶带错",
            "吊牌颜色/尺码错","没吊牌/贴纸/腰牌","无特殊贴纸/贴错","枪针错","成衣质量问题"};
    //拦截扫描枪输入部分
    String BarcodeStr="";
    ScannerManager scannerManager;
    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (scannerManager.dispatchKeyEvent(event)) {
            return true;
        }
        return super.dispatchKeyEvent(event);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_trans);
        InitView();
        //获取登陆参数
        Bundle paramBundle = this.getIntent().getExtras();
        curLoginUserNo=paramBundle.getString("LoginUserNo");
        curLoginUser=paramBundle.getString("LoginUser");
        curLoginTime=paramBundle.getString("LoginTime");
        serviceUrl=paramBundle.getString("serviceUrl");
        serviceUrlExt=paramBundle.getString("serviceUrlExt");
        FormType=paramBundle.getString("FormType");
        Caption=paramBundle.getString("Caption");
        //界面变量
        ((TextView)findViewById(R.id.tv_userName)).setText("用户:"+curLoginUser);
        //置标题颜色
        txt_titleInv.setText(Caption);
        if (FormType.equals("BoxTrans")==true){
            findViewById(R.id.btn_receive).setVisibility(View.GONE);
        }
        if (FormType.equals("BoxTransRec")==true){
            findViewById(R.id.btn_backtrans).setVisibility(View.GONE);
        }
        //将可选内容与ArrayAdapter连接起来
        adapter = new ArrayAdapter<String>(edit_Barcode.getContext(),R.layout.spinner_item,spinnerItem);
        //设置下拉列表的风格
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        //将adapter 添加到spinner中
        spinnerTrans.setAdapter(adapter);
        //添加事件Spinner事件监听
        spinnerTrans.setOnItemSelectedListener(new SpinnerSelectedListener());
        //拦截扫描事件
        scannerManager = new ScannerManager(new ScannerManager.OnScanListener() {
            @Override
            public void onResult(String code) {
                Log.d(TAG, "code= " + code);
                playRingtone();
                edit_Barcode.setText(code);
                ScanBarcode(edit_Barcode.getText().toString(),0);
            }
        });
        selReason=spinnerItem[0];
    }


    //插放音乐;
    private void playRingtone(){
        Uri notification = Uri.parse("android.resource://"+getPackageName()+"/"+R.raw.scan);
        Ringtone r = RingtoneManager.getRingtone(this, notification);
        r.play();

    }


    //判断是否为数字，不然不转
    public static boolean isNumer(String str) {
        try {
            new BigDecimal(str);
            return true;
        } catch (Exception e) {
            return false;
        }
    }



    private void transCancel(String transType) {
        String SqlComm = "Exec App_BoxTransBarcode @BoxNo='" + edt_BoxNo.getText() + "',@FormType='" + FormType
                + "',@OperType='"+transType+ "',@Reason='"+selReason+"',@UserNo='" + curLoginUserNo  + "',@UserName='"+curLoginUser+"'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);

    }


    //dp 转换成px
    public int dp2px(float dp)
    {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics());
    }

    private void InitView(){
        list_Order=findViewById(R.id.list_Order);
        btn_Query=findViewById(R.id.btn_Scan);
        btn_Query.setOnClickListener(this);
        tv_ResultInfo=findViewById(R.id.tv_ResultInfo);
        btn_refreshDetail=findViewById(R.id.btn_refreshDetail);
        btn_refreshDetail.setOnClickListener(this);
        edit_Barcode=findViewById(R.id.edit_Barcode);
        edit_Barcode.setInputType(InputType.TYPE_NULL);
        edit_Barcode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                edit_Barcode.setInputType(InputType.TYPE_CLASS_TEXT);
                //1.得到InputMethodManager对象
                InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                //2.调用showSoftInput方法显示软键盘，其中view为聚焦的view组件
                imm.showSoftInput(edit_Barcode,InputMethodManager.SHOW_FORCED);
            }
        });
        edit_Barcode.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event!=null){
                    //Log.e("Debug","-----------------------------Debug-----------------------------");
                    //System.out.println(event);
                    if ((event.getAction()==KeyEvent.ACTION_UP)&&(event.getKeyCode()== KeyEvent.KEYCODE_ENTER))
                    {
                        //虚拟键盘或实体键盘可考虑是否通过deviceID，或source来判断
                        // KeyEvent:KeyEvent { action=ACTION_DOWN, keyCode=KEYCODE_ENTER, scanCode=0, metaState=0, flags=0x16, repeatCount=0, eventTime=142515176, downTime=142515176, deviceId=-1, source=0x0 }
                        //隐藏键盘
                        //System.out.println(edit_Barcode.getText().toString());
                        ScanBarcode(edit_Barcode.getText().toString(),0);
                        return true;
                    }
                }
                return false;
            }
        });
        edit_Barcode.requestFocus();
        edit_Barcode.requestFocusFromTouch();
        edt_OrderNo=findViewById(R.id.edt_OrderNo);
        edt_BoxNo=findViewById(R.id.edt_BoxNo);
        edt_Item=findViewById(R.id.edt_Item);
        liner_title=findViewById(R.id.liner_title);
        tv_barcodeCaption =findViewById(R.id.tv_barcodeCaption);
        txt_titleInv=findViewById(R.id.txt_titleInv);
        btn_return =findViewById(R.id.btn_return);
        btn_return.setOnClickListener(this);
        //按钮事件
        spinnerTrans=findViewById(R.id.spinnerTrans);
        findViewById(R.id.btn_receive).setOnClickListener(this);
        findViewById(R.id.btn_backtrans).setOnClickListener(this);
    }

    // 隐藏手机键盘
    private void hideIM(View edt) {
        try {
            InputMethodManager im = (InputMethodManager) this.getSystemService(Activity.INPUT_METHOD_SERVICE);
            IBinder windowToken = edt.getWindowToken();
            if (windowToken != null) {
                im.hideSoftInputFromWindow(windowToken, 0);
            }
        } catch (Exception e) {

        }
    }

    @Override
    public void onClick(View view) {
        hideIM(view);
        switch (view.getId()){
            case R.id.btn_return:
                finish();//关闭当前Activity，返回上一级;
                break;
            case R.id.btn_Scan:
                if ((edit_Barcode.getText()!=null)&&(edit_Barcode.getText().length()>0)) {
                    ScanBarcode(edit_Barcode.getText().toString(),0);
                } else Toast.makeText(getApplicationContext(),"请先输入条码!",Toast.LENGTH_LONG).show();
                break;
            case R.id.btn_receive:
                if ((edt_BoxNo.getText()!=null)&&(edt_BoxNo.getText().length()>0)) {
                    transCancel("Receive");
                } else Toast.makeText(getApplicationContext(),"请先输入条码!",Toast.LENGTH_LONG).show();
                break;
            case R.id.btn_backtrans:
                if ((edt_BoxNo.getText()!=null)&&(edt_BoxNo.getText().length()>0)) {
                    transCancel("Retreat");
                } else Toast.makeText(getApplicationContext(),"请先输入条码!",Toast.LENGTH_LONG).show();
                break;
            case R.id.btn_refreshDetail:
                refreshDetail();
                break;
            default:
                break;
        }
    }

    //刷新校验;
    private void refreshDetail(){
        //组织WebService地址;
        try {
            detailJSON=new JSONArray("[]");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String SqlComm="Exec App_BoxTransBarcode @FormType='"+FormType
                +"',@OperType='ScanDetail',@UserNo='" + curLoginUserNo+"'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);
    }

    //订单表格适配器;
    public final class DetailGridAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public DetailGridAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        private JSONArray jsonArray;

        @Override
        public int getCount() {
            return jsonArray.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return jsonArray.get(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) convertView = inflater.inflate(R.layout.activity_trans_item, null, false);
            String tmpValue;
            int pullVatListWidth=parent.getWidth();
            //convertView.setLayoutParams(new ListView.LayoutParams((int)pullVatListWidth,(int)(parent.getHeight()/pageItemCount)));
            int backcolor=getResources().getColor(R.color.white);
            int fontcolor=getResources().getColor(R.color.text_black);
            if (position%2==1) backcolor=getResources().getColor(R.color.listContentColor);
            try {
                TextView tv = (TextView) convertView.findViewById(R.id.item_BoxNo);// 显示文字
                if (jsonArray.optJSONObject(position).has("BoxNo")) tv.setText(jsonArray.optJSONObject(position).get("BoxNo").toString());
                tv = (TextView) convertView.findViewById(R.id.item_Reason);// 显示文字
                if (jsonArray.optJSONObject(position).has("Reason")) tv.setText(jsonArray.optJSONObject(position).get("Reason").toString());
                tv = (TextView) convertView.findViewById(R.id.tv_OrderNo);// 显示文字
                if (jsonArray.optJSONObject(position).has("OrderNo")) tv.setText(jsonArray.optJSONObject(position).get("OrderNo").toString());
                tv = (TextView) convertView.findViewById(R.id.tv_Item);// 显示文字
                if (jsonArray.optJSONObject(position).has("Item")) tv.setText(jsonArray.optJSONObject(position).get("Item").toString());
                tv = (TextView) convertView.findViewById(R.id.tv_StyleNo);// 显示文字
                if (jsonArray.optJSONObject(position).has("StyleNo")) tv.setText(jsonArray.optJSONObject(position).get("StyleNo").toString());
                tv = (TextView) convertView.findViewById(R.id.tv_PO);// 显示文字
                if (jsonArray.optJSONObject(position).has("PO")) tv.setText(jsonArray.optJSONObject(position).get("PO").toString());
                tv = (TextView) convertView.findViewById(R.id.tv_Port);// 显示文字
                if (jsonArray.optJSONObject(position).has("Port")) tv.setText(jsonArray.optJSONObject(position).get("Port").toString());
                tv = (TextView) convertView.findViewById(R.id.tv_BoxFormat);// 显示文字
                if (jsonArray.optJSONObject(position).has("BoxFormat")) tv.setText(jsonArray.optJSONObject(position).get("BoxFormat").toString());
                tv = (TextView) convertView.findViewById(R.id.tv_BoxType);// 显示文字
                if (jsonArray.optJSONObject(position).has("BoxType")) tv.setText(jsonArray.optJSONObject(position).get("BoxType").toString());
                tv = (TextView) convertView.findViewById(R.id.tv_ColorNo);// 显示文字
                if (jsonArray.optJSONObject(position).has("ColorNo")) tv.setText(jsonArray.optJSONObject(position).get("ColorNo").toString());
                tv = (TextView) convertView.findViewById(R.id.tv_Size);// 显示文字
                if (jsonArray.optJSONObject(position).has("Size")) tv.setText(jsonArray.optJSONObject(position).get("Size").toString());

            } catch (JSONException e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }
            Log.d("msg","DetailGridAdapter_position:"+position);
            return convertView;
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        GetSpinnerItem();
    }

    //提交所选择的工序至服务器,然后刷新工序列表;
    private void GetSpinnerItem() {
        try {
            itemJson=new JSONArray("[]");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Runnable run = new Runnable() {
            @Override
            public void run() {
                //将数据读到JSONArray;
                try {
                    String SqlComm = "Exec App_BoxTransBarcode @BoxNo='" + edt_BoxNo.getText() + "',@FormType='" + FormType
                            + "',@OperType='GetSpinner',@UserNo='" + curLoginUserNo  + "',@UserName='"+curLoginUser+"'";
                    Statement stmt = DBUtil.getSQLConnection().createStatement();
                    ResultSet rs = stmt.executeQuery(SqlComm);
                    //取字段相关信息;
                    ResultSetMetaData metaData = rs.getMetaData();
                    int columnCount = metaData.getColumnCount();
                    ArrayList<String> strList =new ArrayList<String>();
                    //遍列数据;
                    while (rs.next()) {
                        JSONObject jsonObj = new JSONObject();
                        // 遍历每一列
                        for (int i = 1; i <= columnCount; i++) {
                            String columnName = metaData.getColumnLabel(i);
                            Object value = rs.getObject(columnName);
                            if (value==null) value="";
                            jsonObj.put(columnName, value);
                        }
                        if (jsonObj.has("Item")){
                            strList.add(jsonObj.getString("Item"));
                        }
                        itemJson.put(jsonObj);
                    }
                    if (strList.size()>0){
                        spinnerItem = strList.toArray(new String[strList.size()]);
                    }
                    //显示预排单;
                    Message msg = new Message();
                    msg.what = MSG_SpinnerOver;
                    handler.removeMessages(msg.what);
                    handler.sendMessage(msg);
                    //消息给创建列;
                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (SQLException e) {
                    e.printStackTrace();
                }catch (Exception e){
                    e.printStackTrace();
                }


            }
        };
        new Thread(run).start();
    }
    //登陆校验;
    private void ScanBarcode(String paramBarcode,int inProgress){
        hideIM(edit_Barcode);
        if (ScanSign==false) {
            ScanSign=true;
            //组织WebService地址;
            edit_Barcode.setEnabled(false);
            edit_Barcode.setText("");
            //刷新表格
            try {
                resultJSON = new JSONArray("[]");
                clearScreen();
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
            String SqlComm = "Exec App_BoxTransBarcode @Barcode='" + paramBarcode + "',@FormType='" + FormType
                    + "',@OperType='ScanBarcode',@UserNo='" + curLoginUserNo  + "',@UserName='"+curLoginUser+"'";
            PrBarcode = paramBarcode;
            //调用WebService过程并处理界面更新;
            ReadSQLData(SqlComm);
        } else Toast.makeText(this,"请稍等或退出重进!",Toast.LENGTH_LONG).show();
    }




    //通过消息来执行处理类程序,不更新UI则不一定需要通过这个;
    final Handler handler = new Handler() {
        @RequiresApi(api = Build.VERSION_CODES.KITKAT)
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            // TODO Auto-generated method stub
            // 根据消息ID来判断要做的事情
            int msgId = msg.what;
            hideIM(edit_Barcode);
            edit_Barcode.setEnabled(true);
            edit_Barcode.selectAll();
            edit_Barcode.requestFocus();
            ScanSign=false;
            switch (msgId) {
                case MSG_SpinnerOver:
                    //将可选内容与ArrayAdapter连接起来
                    adapter = new ArrayAdapter<String>(edit_Barcode.getContext(),R.layout.spinner_item,spinnerItem);
                    //设置下拉列表的风格
                    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                    //将adapter 添加到spinner中
                    spinnerTrans.setAdapter(adapter);
                    //添加事件Spinner事件监听
                    spinnerTrans.setOnItemSelectedListener(new SpinnerSelectedListener());
                    break;
                case MSG_ScanBarcodeOver:
                    if (resultJSON != null) {
                        //填充屏幕
                        fillScreen(resultJSON.optJSONObject(0));
                    }
                case MSG_AllowScan:
                    ScanSign=false;
                    break;
                case MSG_Detail:
                    if (detailJSON != null) {
                        DetailGridAdapter detailGridAdapter = new DetailGridAdapter(getApplicationContext());
                        detailGridAdapter.jsonArray = detailJSON;
                        list_Order.setAdapter(detailGridAdapter);
                    }
                    break;
                default:
                    break;
            }
        }
    };

    //使用数组形式操作
    class SpinnerSelectedListener implements AdapterView.OnItemSelectedListener {

        public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
                                   long arg3) {
            selReason=spinnerItem[arg2];
            //view.setText("你的血型是："+m[arg2]);
        }

        public void onNothingSelected(AdapterView<?> arg0) {
        }
    }

    private void fillScreen(JSONObject optJSONObject) {
        if (optJSONObject!=null){
            try {
                if (optJSONObject.has("BoxNo")) edt_BoxNo.setText(optJSONObject.getString("BoxNo"));
                if (optJSONObject.has("OrderNo")) edt_OrderNo.setText(optJSONObject.getString("OrderNo"));
                if (optJSONObject.has("Item")) edt_Item.setText(optJSONObject.getString("Item"));
                if (optJSONObject.has("StyleNo"))
                    ((TextView)findViewById(R.id.tv_StyleNo)).setText(optJSONObject.getString("StyleNo"));
                if (optJSONObject.has("PO"))
                    ((TextView)findViewById(R.id.tv_PO)).setText(optJSONObject.getString("PO"));
                if (optJSONObject.has("Port"))
                    ((TextView)findViewById(R.id.tv_Port)).setText(optJSONObject.getString("Port"));
                if (optJSONObject.has("BoxFormat"))
                    ((TextView)findViewById(R.id.tv_BoxFormat)).setText(optJSONObject.getString("BoxFormat"));
                if (optJSONObject.has("BoxType"))
                    ((TextView)findViewById(R.id.tv_BoxType)).setText(optJSONObject.getString("BoxType"));
                if (optJSONObject.has("ColorNo"))
                    ((TextView)findViewById(R.id.tv_ColorNo)).setText(optJSONObject.getString("ColorNo"));
                if (optJSONObject.has("Size"))
                    ((TextView)findViewById(R.id.tv_Size)).setText(optJSONObject.getString("Size"));
                if (optJSONObject.has("AllowRec"))
                    if (optJSONObject.getString("AllowRec").equals("Y")) findViewById(R.id.btn_receive).setVisibility(View.VISIBLE);
                    else  findViewById(R.id.btn_receive).setVisibility(View.GONE);
                if (optJSONObject.has("AllowBack"))
                    if (optJSONObject.getString("AllowBack").equals("Y")) findViewById(R.id.btn_backtrans).setVisibility(View.VISIBLE);
                    else  findViewById(R.id.btn_backtrans).setVisibility(View.GONE);
                if (optJSONObject.has("ResultInfo")) ((TextView) findViewById(R.id.tv_ResultInfo)).setText(optJSONObject.getString("ResultInfo"));
                if (optJSONObject.has("ErrInfo") == true) {
                    //MediaPlayer mediaPlayer = MediaPlayer.create(getActivity(), R.raw.warn);
                    //mediaPlayer.start();
                    AlertDialog alertDialog = new AlertDialog.Builder(this)
                            .setTitle(getString(R.string.SystemHint)).setMessage(optJSONObject.getString("ErrInfo"))
                            .setPositiveButton(getString(R.string.Affirm), new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    hideIM(edit_Barcode);
                                    edit_Barcode.selectAll();
                                    edit_Barcode.requestFocus();
                                    return;
                                }
                            }).create(); // 创建对话框
                    alertDialog.show(); // 显示对话框
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }


    private void clearScreen() {
        edt_BoxNo.setText("");
        edt_Item.setText("");
        edt_OrderNo.setText("");
        ((TextView)findViewById(R.id.tv_StyleNo)).setText("");
        ((TextView)findViewById(R.id.tv_PO)).setText("");
        ((TextView)findViewById(R.id.tv_Port)).setText("");
        ((TextView)findViewById(R.id.tv_BoxFormat)).setText("");
        ((TextView)findViewById(R.id.tv_BoxType)).setText("");
        ((TextView)findViewById(R.id.tv_ColorNo)).setText("");
        ((TextView)findViewById(R.id.tv_Size)).setText("");
    }
    //直接连获取数据，与Handler配套使用;
    private void ReadSQLData(final String SQLComm) {
        ScanSign=true;
        Runnable run = new Runnable() {
            @Override
            public void run() {
                try{
                    JSONArray jsonArray  = DBUtil.QuerySQL2JSON(SQLComm);
                    System.out.println(jsonArray);
                    ScanSign=false;
                    //往界面转数据;
                    if ((jsonArray!=null)&&(jsonArray.length()>0)) {
                        if (jsonArray.optJSONObject(0).has("OperType")){
                            if (jsonArray.optJSONObject(0).getString("OperType").equals("ScanBarcode")==true
                            ||jsonArray.optJSONObject(0).getString("OperType").equals("Receive")==true
                            ||jsonArray.optJSONObject(0).getString("OperType").equals("Retreat")==true){
                                resultJSON =jsonArray;
                                //刷新界面;
                                Message msg = new Message();
                                msg.what = MSG_ScanBarcodeOver;
                                handler.removeMessages(msg.what);
                                handler.sendMessage(msg);
                            }
                            if (jsonArray.optJSONObject(0).getString("OperType").equals("ScanDetail")==true){
                                detailJSON =jsonArray;
                                //刷新界面;
                                Message msg = new Message();
                                msg.what = MSG_Detail;
                                handler.removeMessages(msg.what);
                                handler.sendMessage(msg);
                            }

                        }
                    } else{
                        Message msg = new Message();
                        msg.what = MSG_AllowScan;
                        handler.removeMessages(msg.what);
                        handler.sendMessage(msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    //刷新界面;
                    ScanSign=false;
                    Message msg = new Message();
                    msg.what = MSG_AllowScan;
                    handler.removeMessages(msg.what);
                    handler.sendMessage(msg);
                }

            }

        };
        new Thread(run).start();

    }





    //从字符串转颜色
    private int GetColorValue(String paramColor){
        int PenColor= Color.WHITE;
        String StrPenColor=paramColor;
        if ((StrPenColor.indexOf("#")==0)&&(StrPenColor.length()==7)){
            int testColor=Integer.parseInt(StrPenColor.substring(1),16);
            int red = (testColor & 0xff0000) >> 16;
            int green = (testColor & 0x00ff00) >> 8;
            int blue = (testColor & 0x0000ff);
            PenColor=Color.rgb(red, green, blue);
        }else {
            if (isNumer(StrPenColor)) {
                int testColor = Integer.parseInt(StrPenColor);
                int red = (testColor & 0xff0000) >> 16;
                int green = (testColor & 0x00ff00) >> 8;
                int blue = (testColor & 0x0000ff);
                PenColor = Color.rgb(red, green, blue);
            } else {
                if (StrPenColor.equals("Black") == true)
                    PenColor = Color.BLACK;
                if (StrPenColor.equals("Blue") == true)
                    PenColor = Color.BLUE;
                if (StrPenColor.equals("Yellow") == true)
                    PenColor = Color.YELLOW;
                if (StrPenColor.equals("Red") == true)
                    PenColor = Color.RED;
                if (StrPenColor.equals("Green") == true)
                    PenColor = Color.GREEN;
                if (StrPenColor.equals("Gray") == true)
                    PenColor = Color.LTGRAY;
                if (StrPenColor.equals("White") == true)
                    PenColor = Color.WHITE;
            }
        }
        return PenColor;
    }



}